/************************************************************************
This file is part of ts3300 package for the simpleRTJ virtual machine.

This file is covered by the GNU GPL with the following exception:
  As a special exception, the copyright holders of this library give you permission
  to link this library with independent modules to produce an executable, regardless
  of the license terms of these independent modules, and to copy and distribute the
  resulting executable under terms of your choice, provided that you also meet, for
  each linked independent module, the terms and conditions of the license of that
  module. An independent module is a module which is not derived from or based on
  this library. If you modify this library, you may extend this exception to your
  version of the library, but you are not obligated to do so. If you do not wish
  to do so, delete this exception statement from your version.


THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY,  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL RTJ COMPUTING BE LIABLE FOR ANY CLAIM, DAMAGES
OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

Copyright (c) 2000-2006 RTJ Computing Pty. Ltd. All rights reserved.
***********************************************************************/
package lpc2xxx.edu;

import lpc2xxx.hw.*;

/**
 * LCD class allows writing messages to standard text based LCD panels based on Hitachi HD44780
 * connected to GPIO pins on LPC2148 Education Board.<p>
 * Four-bit data interface is used to send commands and data to the LCD panel. This frees five GPIO 
 * pins for other uses. Pins usage:<br>
 * <code>
 * P1.20-23 - data bits (D4-D7)<br>
 * P1.24    - RS signal<br>
 * P1.25    - E signal<br>
 * P0.30    - backlight control<br>
 * </code>
 * <p>
 * This class can handle LCD panels with up to four lines and 20 characters per line. 
 * It can be easily adapted to handle displays with the different character layouts.
 */
public class LCD
{
    /** Starting address of Line 1 */
    public final static int LINE1      = 0x00;
    /** Starting address of Line 2 */
    public final static int LINE2      = 0x40;
    /** Starting address of Line 3 */
    public final static int LINE3      = 0x14;
    /** Starting address of Line 4 */
    public final static int LINE4      = 0x54;
    /** Identifies <i>left</i> text alignment */
    public final static int LEFT       = 1;
    /** Identifies <i>center</i> text alignment */
    public final static int CENTER     = 2;
    /** Identifies <i>right</i> text alignment */
    public final static int RIGHT      = 3;

    private final static int RS = GPIO.P24;
    private final static int E = GPIO.P25;
    private final static int LIGHT = GPIO.P30;

    private final static boolean CMD    = true;
    private final static boolean DATA   = false;

    private static boolean initialized = false;
    private char buffer[];
    private int maxLines = 1;
    private int maxCols = 16;

    private static GPIO p0 = new GPIO(GPIO.PORT0);
    private static GPIO p1 = new GPIO(GPIO.PORT1);

    /** 
     * Creates an instance of the LCD class and performs LCD initiaziation.
     * @param lines number of lines
     * @param columns number of columns 
     */
    public LCD(int lines, int columns) 
    {
        if (lines >= 1 && lines <= 4)
            maxLines = lines;
        if (columns == 20 || columns == 40)
            maxCols = columns;

        buffer = new char[maxCols];
        init();
    }

    /**
     * Clears the whole display.
     */
    public void clearDisp() 
    {
        for (int i=1; i <= maxLines; i++)
        {
            int addr = LINE1;
            switch (i)
            {
                case 2: addr = LINE2; break;
                case 3: addr = LINE3; break;
                case 4: addr = LINE4; break;
            }
            clearLine(addr);
        }
    }

    /**
     * Sets each array element to space (0x20) character.
     * @param arr destination char array that will have all elements set to 0x20
     */
    private void clearBuff(char arr[])
    {
        for (int i=0; i < arr.length; i++)
            arr[i] = ' ';
    }

    /**
     * Takes the text in the source array and outputs it centered in the destination array.<br>
     * Destination array must be big enough to hold one line.
     * @param src array with text to center
     * @param dest array where the centered text will be output
     */
    public void centerText(char src[], char dest[])
    {
        clearBuff(dest);
        if (dest.length < maxCols)
            return;
        
        int start = (maxCols - src.length) >> 1;
        start = start < 0 ? 0 : start;
        int len = src.length > maxCols ? maxCols : src.length;

        for (int i=0; i < len; i++)
            dest[start+i] = src[i];
    }

    /**
     * Displays the text message on the specified line.
     * @param line line number 
     * @param msg text to display as array of chars
     * @param align text alignment: LEFT, CENTER or RIGHT
     */
    public void showLine(int line, char[] msg, int align)
    {
        clearBuff(buffer);
        int len = msg.length > maxCols ? maxCols : msg.length;
        switch (align)
        {
            case LEFT:
                System.arraycopy(msg, 0, buffer, 0, len);
                break;
            case CENTER:
                System.arraycopy(msg, 0, buffer, (maxCols-len)/2, len);
                break;
            case RIGHT:
                System.arraycopy(msg, 0, buffer, maxCols-len, len);
                break;
        }
        showLine(line, buffer);
    }

    /**
     * Displays the text message on the specified line.
     * @param line line number ; use LINEn constants
     * @param msg text to display as String object
     * @param align text alignment: LEFT, CENTER or RIGHT
     */
    public void showLine(int line, String msg, int align)
    {
        clearBuff(buffer);
        int len = msg.length() > maxCols ? maxCols : msg.length();
        switch (align)
        {
            case LEFT:
                msg.getChars(0, len, buffer, 0);
                break;
            case CENTER:
                msg.getChars(0, len, buffer, (maxCols-len)/2);
                break;
            case RIGHT:
                msg.getChars(0, len, buffer, maxCols-len);
                break;
        }
        showLine(line, buffer);
    }

    /**
     * Displays single character at the specifield line and column.
     * @param line line number; use LINEn constants
     * @param col starting position on the line; 0 to Columns-1
     * @param ch character to display
     */
    public void showAt(int line, int col, char ch)
    {
        int addr = -1;
        switch (line)
        {
            case LINE1:
            case LINE2:
            case LINE3:
            case LINE4:
                addr = line + col;
                break;
        }
        if (addr >= 0)
            setChar(addr, ch);
    }

    /**
     * Displays the integer value at the specified line and column position.
     * @param line line number; use LINEn constants
     * @param col starting position on the line
     * @param numb integer value to display
     * @param len number of digits to display; if the value is less then len a '0'
     *        character is prepended.
     */
    public void showInt(int line, int col, int numb, int len)
    {
        i2a(numb, len, '0', buffer, 0);
        for (int i=0; i < len; i++)
            showAt(line, col+i, buffer[i]);
    }

    /**
     * Converts integer into string ASCII characters.
     * @param value integer value to convert
     * @param digits max. number of digits
     * @param fill left fill character if value is shorter than max. number of digits
     * @param dest char array
     * @param offs into destination array
     */
    public static void i2a(int value, int digits, char fill, char[] dest, int offs)
    {
        if (dest == null || digits < 1 || offs < 0 || dest.length < offs + digits)
            return;

        // fill from right to left
        for (int i=digits-1; i >= 0; i--)
        {
            int rem = (value % 10);
            dest[offs + i] = rem == 0 && i != digits - 1 && value == 0 ? fill : (char)(rem + 0x30);
            value /= 10;
        }
    }

    /**
     * Clears the specified line.
     * @param line line number; use LINEn constants
     */
    public synchronized void clearLine(int line)
    {
        clearBuff(buffer);
        showLine(line, buffer);
    }
    
    /**
     * Displays the text message on the specified line.
     * @param line line address; use LINEn constants
     * @param msg message to display as char array
     */
    public static synchronized void showLine(int line, char[] msg)
    {
        if (msg != null && msg.length > 0)
        {
            send(line | 0x80, CMD);
            for (int i=0; i < msg.length; i++)
                send(msg[i], DATA);
        }
    }

    /**
     * Writes one character at specified memory address.
     * @param pos memory address in LCD controller where the character should be written.
     * @param val character to display at specified address.
     */
    private static synchronized void setChar(int pos, char val)
    {
        send(pos | 0x80, CMD);
        send(val, DATA);
    }

    /**
     * Turns backight on.
     */
    public void backlightOn()
    {
        p0.set(LIGHT);
    }

    /**
     * Turns backight off.
     */
    public void backlightOff()
    {
        p0.clear(LIGHT);
    }

    /** 
     * Initialises the LCD controller.
     */
    private static synchronized void init()
    {
        if (initialized)
            return;

        GPIO.config(1, 0xCFFFFFFF, 0);
        GPIO.config(2, 0, 0);
        p0.dirOut(p0.P30);
        p1.dirOut(p1.P20 | p1.P21 | p1.P22 | p1.P23 | p1.P24 | p1.P25);
        
        p1.clear(E);
        p1.clear(RS);
        // 3x init cmd
        sendNibble(0x3);
        sleep(10);
        sendNibble(0x3);
        sleep(5);
        sendNibble(0x3);
        sleep(5);
        // set 4-bit interface
        sendNibble(2);
        sleep(5);
        
        send(0x28, CMD);    // function set: 5x7, 2 line
        send(0x08, CMD);    // display off
        send(0x01, CMD);    // display on
    	send(0x06, CMD);    // entry mode: auto incr. and no shift
        send(0x0C, CMD);    // enable display and optional cursor

        initialized = true;
    }

    /**
     * Sends a command to LCD controller as two 4-bit long words.
     * @param cmd command function
     */
    private static synchronized void send(int val, boolean cmd)
    {
        if (cmd)
            p1.clear(RS);
        else
            p1.set(RS);
        sendNibble(val >> 4);
        sendNibble(val);
    }

    /** 
     * Outputs 4-bit value to P1.20-23
     * @param val 4-bit value
     */
    private static synchronized void sendNibble(int val)
    {
        //p1.clear(p1.P16 | p1.P17 | p1.P18 | p1.P19);
        p1.clear(p1.P20 | p1.P21 | p1.P22 | p1.P23);
/*
        if ((val & 1) == 1)
            p1.set(p1.P16);
        if ((val & 2) == 2)
            p1.set(p1.P17);
        if ((val & 4) == 4)
            p1.set(p1.P18);
        if ((val & 8) == 8)
            p1.set(p1.P19);
        if ((val & 16) == 16)
            p1.set(p1.P20);
        if ((val & 32) == 32)
            p1.set(p1.P21);
        if ((val & 64) == 64)
            p1.set(p1.P22);
        if ((val & 128) == 128)
            p1.set(p1.P23);
*/
        if ((val & 1) == 1)
            p1.set(p1.P20);
        if ((val & 2) == 2)
            p1.set(p1.P21);
        if ((val & 4) == 4)
            p1.set(p1.P22);
        if ((val & 8) == 8)
            p1.set(p1.P23);

        p1.set(E);
        p1.clear(E);
    }

    /**
     * Sleeps for the specified numbers of milliseconds.
     * @param ms number of milliseconds to suspend code execution.
     */
    private static void sleep(int ms)
    {
        try
        {
            Thread.sleep(ms);
        }
        catch (InterruptedException e) {}
    }
}

